//
//  UIImage+LSF.swift
//  hoonpay
//
//  Created by 李胜锋 on 2017/8/18.
//  Copyright © 2017年 lishengfeng. All rights reserved.
//

import Foundation
import UIKit
import AVFoundation

extension UIImage {
    
    ///通过UIColor 生成图片
    static func lsf_image(color:UIColor, size:CGSize) -> UIImage? {
        
        let rect = CGRect.init(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContext(size)
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
    
    //*
    func lsf_fixOrientation () -> UIImage {
        if self.imageOrientation == .up {
            return self
        }
        
        var transform : CGAffineTransform = CGAffineTransform.identity
        
        switch  self.imageOrientation {
        case .down, .downMirrored:
            transform = transform.translatedBy(x: self.size.width, y: self.size.height)
            transform = transform.rotated(by: CGFloat.pi)
            
        case .left, .leftMirrored:
            transform = transform.translatedBy(x: self.size.width, y: 0)
            transform = transform.rotated(by: CGFloat.pi / 2.0)
            
            
        case .right, .rightMirrored:
            transform = transform.translatedBy(x: 0, y: self.size.height)
            transform = transform.rotated(by: -CGFloat.pi / 2.0)
            
        default:
            break
        }
        
        switch self.imageOrientation {
        case .upMirrored, .downMirrored:
            transform = transform.translatedBy(x: self.size.width, y: 0)
            transform = transform.scaledBy(x: -1, y: 1)
            
        case .leftMirrored, .rightMirrored:
            transform = transform.translatedBy(x: self.size.height, y: 0)
            transform = transform.scaledBy(x: -1, y: 1)
            
        default:
            break
        }
        
        let ctx = CGContext.init(data: nil, width: Int(self.size.width), height: Int(self.size.height), bitsPerComponent: self.cgImage!.bitsPerComponent, bytesPerRow: 0, space: self.cgImage!.colorSpace!, bitmapInfo: self.cgImage!.bitmapInfo.rawValue)
        ctx?.concatenate(transform)
        
        switch self.imageOrientation {
        case .left, .leftMirrored, .right, .rightMirrored:
            ctx?.draw(self.cgImage!, in: CGRect.init(x: 0, y: 0, width: size.height, height: size.width))
        default:
            ctx?.draw(self.cgImage!, in: CGRect.init(x: 0, y: 0, width: size.width, height: size.height))
        }
        
        let cgimg = ctx?.makeImage()
        let img = UIImage.init(cgImage: cgimg!)
        
        return img
        
    }
 
 // */
}

